﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using AKMII.DMRA.Business.Management;
using AKMII.DMRA.Business.Rule;
using AKMII.DMRA.Common;
using System.IO;

namespace AKMII.DMRA.Web
{
    public partial class OrderMap : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SurveyDiv1.OnOkClick += new EventHandler(ChangePasswordDiv1_OnOkClick);
            SurveyDiv1.OnCancelClick += new EventHandler(ChangePasswordDiv1_OnCancelClick);

            if (!IsPostBack)
            {
                ShowSurveyDiv();
                BindStep1Drp();
                BindStep2Drp();
                DateTime lastMonthDate = new DateTime(CurrentPeriod.Year, CurrentPeriod.Month, 1).AddMonths(-1);
                hideLastMonthDate.Value = Utility.GetNumber(lastMonthDate.Month) + lastMonthDate.Year.ToString();
                Session["UserName"] = User.Identity.Name.ToString();
                OrderManager om = new OrderManager();
                Order order = om.GetOrder(HttpContext.Current.Session["UserName"].ToString(), CurrentPeriod.Month, CurrentPeriod.Year);
                if (order == null)
                {
                    order = new Order();
                    order.PeroidMonth = CurrentPeriod.Month;
                    order.PeroidYear = CurrentPeriod.Year;
                    order.AccountId = HttpContext.Current.Session["UserName"].ToString();
                }
                Session["isFilter"] = false;
                Session["sortDirection"] = "Ascending";
                BindDrpdownLists();
            }
        }

        protected void ChangePasswordDiv1_OnOkClick(object sender, EventArgs e)
        {
            try
            {
                using (FileStream fs = new FileStream(Server.MapPath(@"~\survey.txt"), FileMode.Append))
                {
                    StreamWriter sw = new StreamWriter(fs);
                    sw.WriteLine(User.Identity.Name.ToLower() + CurrentPeriod.Month.ToString() + CurrentPeriod.Year.ToString());
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }

                SurveyDiv1.Visible = false;
                //Response.Redirect(Constants.OrderMapPage);
            }
            catch (Exception ex)
            {
                Logger.Error("Exception in writing survey txt", ex);
                throw new ApplicationException("Exception in writing survey txt", ex);
            }
        }

        protected void ChangePasswordDiv1_OnCancelClick(object sender, EventArgs e)
        {
            SurveyDiv1.Visible = false;
            FormsAuthentication.SignOut();
            Response.Redirect(Constants.LoginUrl);
        }

        private void ShowSurveyDiv()
        {
            try
            {
                using (FileStream fs = new FileStream(Server.MapPath(@"~\survey.txt"), FileMode.OpenOrCreate))
                {
                    StreamReader sr = new StreamReader(fs);
                    string reportResult = sr.ReadToEnd();

                    if (reportResult.IndexOf(User.Identity.Name.ToLower() + CurrentPeriod.Month.ToString() + CurrentPeriod.Year.ToString(),
                        StringComparison.CurrentCultureIgnoreCase) == -1)
                    {
                        SurveyDiv1.Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception in opening survey txt,", ex);
                throw new ApplicationException("Exception in opening survey txt,", ex);
            }
        }

        #region old code
        public string GetActiveLeadCount()
        {
            string leadCount = string.Empty;
            User user = Session["CurrentUser"] as User;
            if (user != null)
            {
                leadCount = (user.AgentNumber * SystemConfiguration.CommonSetting.LeadPerAgent * 4).ToString();
            }
            else
            {
                FormsAuthentication.SignOut();
                Response.Redirect(Constants.LoginUrl);
            }
            return leadCount;
        }

        #region public WebMethods
        [WebMethod]
        public static string Pin(string city, string[] counties, string month)
        {
            List<string> cities = city.Split('|').Where(c => !string.IsNullOrEmpty(c)).ToList<string>();
            string countyStr = string.Empty;

            countyStr = counties.Aggregate((a, b) => { return a + "," + b; });

            DateTime inputDateTime = GetInputDateTime(int.Parse(month));

            ZipManager zm = new ZipManager();
            List<SimpleLeadBlock> zips = zm.GetSimpleZipsById(HttpContext.Current.Session["UserName"].ToString(),
                inputDateTime.Month, inputDateTime.Year, 0, countyStr, cities);

            HttpContext.Current.Session["cities"] = city;
            HttpContext.Current.Session["county"] = countyStr;
            HttpContext.Current.Session["orderMonth"] = inputDateTime.Month;
            HttpContext.Current.Session["orderYear"] = inputDateTime.Year;
            HttpContext.Current.Session["Zips"] = zips;

            JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());
            serializer.MaxJsonLength = 2147483647;
            return serializer.Serialize(zips);
        }

        [WebMethod]
        public static void AssignZips(string zipId, string agentName, string month, string year)
        {
            ZipManager zipManager = new ZipManager();
            List<int> zips = new List<int>();
            zips.Add(int.Parse(zipId));

            DateTime inputDateTime = GetInputDateTime(int.Parse(month));
            zipManager.AssignLeadBlock(agentName, zips, inputDateTime.Month, inputDateTime.Year);
        }

        [WebMethod]
        public static string ZipPin()
        {
            ZipManager zm = new ZipManager();
            List<ZipCode> zipCodes = zm.GetZipCodes(HttpContext.Current.Session["UserName"].ToString(), CurrentPeriod.Month, CurrentPeriod.Year);
            JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());
            serializer.MaxJsonLength = 2147483647;
            String zipStr = serializer.Serialize(zipCodes);
            return zipStr;
        }
        [WebMethod]
        public static string LeadsPin(string ZIPId)
        {
            LeadManager lm = new LeadManager();
            List<Lead> leads = lm.GetLeadsByLeadBlockCode(int.Parse(ZIPId));
            JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());
            serializer.MaxJsonLength = 2147483647;
            String leadStr = serializer.Serialize(leads);
            return leadStr;
        }

        [WebMethod]
        public static string LeadsPinWithCity(string[] zipId)
        {
            LeadManager lm = new LeadManager();
            List<Lead> leads = lm.GetLeadsByZipId(zipId.Select(c => int.Parse(c)).ToList<int>());
            JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());
            serializer.MaxJsonLength = 2147483647;
            String leadStr = serializer.Serialize(leads);
            return leadStr;
        }

        [WebMethod]
        public static void ManagerZipToCart(string ZipID, string operateType, string agentName, string orderWeek, string month)
        {
            DateTime inputDateTime = GetInputDateTime(int.Parse(month));
            Order order = new Order();
            LeadBlock zip = new LeadBlock();

            zip.ZipId = int.Parse(ZipID);
            order.Zips.Add(zip);
            order.AccountId = HttpContext.Current.Session["UserName"].ToString();
            order.PeroidYear = inputDateTime.Year;
            order.PeroidMonth = inputDateTime.Month;

            OrderManager om = new OrderManager();
            om.ManageOrder(order, int.Parse(operateType), agentName, int.Parse(orderWeek));
        }
        [WebMethod]
        public static void ManagerZipToCartNew(string[] ZipID, string operateType, string agentName, string orderWeek, string month)
        {
            DateTime inputDateTime = GetInputDateTime(int.Parse(month));
            Order order = new Order();
            order.AccountId = HttpContext.Current.Session["UserName"].ToString();
            order.PeroidYear = inputDateTime.Year;
            order.PeroidMonth = inputDateTime.Month;

            //foreach (var id in ZipID.Distinct().ToList<string>())
            //{
            //    LeadBlock lb = new LeadBlock() { ZipId = int.Parse(id) };
            //    order.Zips.Add(lb);
            //}

            ZipID.Distinct().ToList<string>().ForEach(
                c =>
                {
                    LeadBlock lb = new LeadBlock() { ZipId = int.Parse(c) };
                    order.Zips.Add(lb);
                });

            new OrderManager().ManageOrder(order, int.Parse(operateType), agentName, int.Parse(orderWeek));
        }
        [WebMethod]
        public static void ManagerZipCodeToCart(string ZipName, string operateType)
        {
            Order order = new Order();
            order.AccountId = HttpContext.Current.Session["UserName"].ToString();
            order.PeroidYear = CurrentPeriod.Year;
            order.PeroidMonth = CurrentPeriod.Month;
            OrderManager om = new OrderManager();
            om.ManageOrder(order, int.Parse(operateType), ZipName);
        }
        [WebMethod]
        public static bool IsRuleEnalbe()
        {
            User user = HttpContext.Current.Session["CurrentUser"] as User;
            return user.IsRuleEnabled;
        }
        [WebMethod]
        public static bool IsRuleRepeatEnalbe()
        {
            User user = HttpContext.Current.Session["CurrentUser"] as User;
            return user.IsRepeatRuleEnabled;
        }
        [WebMethod]
        public static bool IsOrderPeriod()
        {
            return CurrentPeriod.IsOrderPeriod;
        }
        [WebMethod]
        public static string BindCity(string[] counties)
        {
            string cityStr = string.Empty;
            if (counties != null && counties.Length > 0)
            {
                LeadManager lm = new LeadManager();
                List<string> cities = new List<string>();
                foreach (var county in counties)
                {
                    cities.AddRange(lm.GetCity(HttpContext.Current.User.Identity.Name, county));
                }

                JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());
                serializer.MaxJsonLength = 2147483647;
                cityStr = serializer.Serialize(cities);
            }

            return cityStr;
        }
        [WebMethod]
        public static string GetLockMonth()
        {
            return SystemConfiguration.CommonSetting.LockMonth.ToString();
        }
        [WebMethod]
        public static int GetSysMonth()
        {
            return CurrentPeriod.Month;
        }
        [WebMethod]
        public static int GetSysYear()
        {
            return CurrentPeriod.Year;
        }
        [WebMethod]
        public static string addAssign(string assignName)
        {
            AccountManager accountManager = new AccountManager();
            Agent agent = new Agent();
            agent.MdNumber = HttpContext.Current.Session["UserName"].ToString();
            agent.Name = assignName;
            accountManager.CreateAgent(agent);

            List<Agent> agents = accountManager.GetAgents(HttpContext.Current.Session["UserName"].ToString());
            //foreach (var agent1 in agents)
            //{
            //    if (agent1.Name == assignName)
            //    {
            //        return agent1.Id.ToString();
            //    }
            //}
            //return Convert.ToString(agents[agents.Count - 1].Id + 1);

            if (agents.Exists(c => c.Name == assignName))
            {
                return agents.First(c => c.Name == assignName).Id.ToString();
            }
            else
            {
                return (agents.Last().Id + 1).ToString();
            }
        }
        [WebMethod]
        public static string IsAssignExist(string assginName)
        {
            Agent agent = new AccountManager().GetAgent(null, assginName);

            return agent.Id != 0 ? "1|" + assginName : "0|" + assginName;
        }

        [WebMethod]
        public static void InsertRepeatEnable(string month, string zipid, string reason)
        {
            DateTime inputDateTime = GetInputDateTime(int.Parse(month));
            OrderManager om = new OrderManager();
            om.InsertOrderRepeatRemark(HttpContext.Current.User.Identity.Name,
                inputDateTime.Month, inputDateTime.Year, int.Parse(zipid), reason);
        }
        [WebMethod]
        public static string SetAgentNameAndLocation(string agentName, string orderWeek, string month, string weekCount)
        {
            HttpContext.Current.Session["agentName"] = agentName;
            HttpContext.Current.Session["orderWeek"] = orderWeek;
            HttpContext.Current.Session["month"] = month;
            HttpContext.Current.Session["weekCount"] = weekCount;

            Agent agent = new AccountManager().GetAgent(HttpContext.Current.User.Identity.Name, agentName);

            return agent.Latitude + "|" + agent.Longitude;
        }
        [WebMethod]
        public static string GetOtherPagePara()
        {
            return HttpContext.Current.Session["agentName"].ToString() + "|" + HttpContext.Current.Session["orderWeek"].ToString() + "|" + HttpContext.Current.Session["month"].ToString() + "|" +
            HttpContext.Current.Session["weekCount"].ToString() + "|" + HttpContext.Current.Session["county"].ToString();
        }
        [WebMethod]
        public static string GetCity()
        {
            return HttpContext.Current.Session["cities"].ToString();
        }
        [WebMethod]
        public static string GetOperateType()
        {
            if (HttpContext.Current.Session["operateType"] == null)
            {
                return "";
            }
            else
            {
                return HttpContext.Current.Session["operateType"].ToString();
            }
        }
        [WebMethod]
        public static void ClearPara()
        {
            HttpContext.Current.Session["operateType"] = null;
        }
        [WebMethod]
        public static string TeerByAgentName(string agentName)
        {
            AccountManager am = new AccountManager();
            Agent agent = am.GetAgent(HttpContext.Current.Session["UserName"].ToString(), agentName);

            return agent.Territory;
        }
        #endregion
        private void BindDrpdownLists()
        {
            LeadManager leadManager = new LeadManager();
            AccountManager accountManager = new AccountManager();
            List<Agent> agents = accountManager.GetAgents(User.Identity.Name);
            //foreach (var agent in agents)
            //{
            //    this.drpAssignment.Items.Add(new ListItem(agent.Name, agent.Id.ToString()));
            //}
            agents.ForEach(c => { drpAssignment.Items.Add(new ListItem(c.Name, c.Id.ToString())); });
            this.drpAssignment.Items.Insert(0, new ListItem("Select Agent", "0"));
            this.lblLower.Text = SystemConfiguration.CommonSetting.MinStop.ToString();
            this.lblUpper.Text = SystemConfiguration.CommonSetting.MaxStop.ToString();
        }


        #endregion
        private void BindStep1Drp()
        {
            AccountManager ac = new AccountManager();
            List<Agent> agents = ac.GetAgentsWithoutOrder(User.Identity.Name);

            agents.ForEach(c => { this.drpOrderAgent.Items.Add(new ListItem(c.Name, c.Id.ToString())); });

            this.drpOrderAgent.Attributes.Add("onchange", "UpdateTerrByAgent()");

            if (agents != null && agents.Count > 0)
            {
                this.hideAgentTerr.Value = agents[0].Territory;
            }

            string[] Months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
            int currentMonth = CurrentPeriod.Month;
            for (int i = 1; i <= 5; i++)
            {
                if (currentMonth > 12)
                {
                    currentMonth = currentMonth - 12;
                }
                ListItem li = new ListItem();
                li.Text = Months[currentMonth - 1];
                li.Value = currentMonth.ToString();
                this.drpOrderMonth.Items.Add(li);
                currentMonth++;
            }

        }
        private void BindStep2Drp()
        {
            LeadManager leadManager = new LeadManager();
            if (Application["County"] == null)
            {

                Application["County"] = leadManager.GetCounty();
            }

            var counties = (Application["County"] as List<Pair<string, string>>).FindAll(c => c.First.Equals(User.Identity.Name, StringComparison.CurrentCultureIgnoreCase));
            DrpOrderCounty.Items.Add("All");

            counties.ForEach(c => { DrpOrderCounty.Items.Add(c.Second); });

            DrpOrderCounty.Attributes.Add("onchange", "UpdateCityByCounty()");
        }

        private static DateTime GetInputDateTime(int month)
        {
            DateTime current = new DateTime(CurrentPeriod.Year, CurrentPeriod.Month, 1);
            int diffMonths = 0;

            diffMonths = (month >= current.Month) ? (month - current.Month) : (12 - current.Month + month);
            DateTime inputDateTime = current.AddMonths(diffMonths);

            return inputDateTime;
        }

        [WebMethod]
        public static void SetCurrentWeek(int week)
        {
            HttpContext.Current.Session["orderWeek"] = week.ToString();
        }
    }
}